package qualomelhor.server;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginTwitterServlet extends HttpServlet {
    private static final long serialVersionUID = -6205814293093350242L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer("uTj7h9PgJOP1Jld9ny1vNg", "7pinRWRQKDvgLLuc4dMA5pWyubIb5767rStjrLagY");
        request.getSession().setAttribute("twitter", twitter);

        String tweet = request.getParameter("tweetComment"); 
        if (tweet != null) {
        	System.out.println("login para postar o tweet..");
        	request.getSession().setAttribute("tweetComment", tweet);	
        }

        try {
            StringBuffer callbackURL = request.getRequestURL();
            int index = callbackURL.lastIndexOf("/");
            callbackURL.replace(index, callbackURL.length(), "").append("/callbackTwitter");

            System.out.println("callback toString = " + callbackURL.toString());
            RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
            request.getSession().setAttribute("requestToken", requestToken);

            System.out.println("requestToken.getAuthenticationURL() = " + requestToken.getAuthenticationURL());
            response.sendRedirect(requestToken.getAuthenticationURL());

        } catch (TwitterException e) {
            throw new ServletException(e);
        }
    }
}